<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts';

export default {
  name: "map-view",
  data() {
    return {
      map: null,
      points: [],
      markers: [],
      districtPoints: {},
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    fetchEquipmentList() {
      getequipmentlist({ limit: 10000000 })
        .then(res => {
          this.points = res.msg.filter(item => item.lat && item.lng).map(item => ({
            lnglat: [parseFloat(item.lng), parseFloat(item.lat)],
            district: 'Unknown', // 初始设置为 'Unknown'
          }));
          this.getDistrictInfo();
        })
        .catch(error => {
          console.error('Error fetching equipment list:', error);
        });
    },
    getDistrictInfo() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.Geocoder"], // 使用地理编码插件
      })
      .then(AMap => {
        const geocoder = new AMap.Geocoder();
        const promises = this.points.map(point => {
          return new Promise(resolve => {
            geocoder.getAddress(point.lnglat, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const district = result.regeocode.addressComponent.district || 'Unknown';
                point.district = district;
                if (!this.districtPoints[district]) {
                  this.districtPoints[district] = [];
                }
                this.districtPoints[district].push(point);
              }
              resolve();
            });
          });
        });

        Promise.all(promises).then(() => {
          this.initMarkers();
          this.showDistrictClusters();
        });
      })
      .catch(error => {
        console.error('Error fetching district info:', error);
      });
    },
    initAMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.Scale", "AMap.Geolocation"], // 需要使用的插件列表
      })
      .then(AMap => {
        this.map = new AMap.Map("container", {
          viewMode: "3D", // 是否为3D地图模式
          zoom: 4, // 初始化地图级别
          center: [116.397428, 39.90923], // 初始化地图中心点位置
          mapStyle: "amap://styles/blue", // 使用高德提供的地图样式
        });

        // 添加比例尺
        this.map.addControl(new AMap.Scale());

        // 浏览器定位
        this.map.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认:true
            timeout: 10000, // 超过10秒后停止定位，默认：5s
            buttonOffset: new AMap.Pixel(10, 20), // 定位按钮的停靠位置
            zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
          });
          this.map.addControl(geolocation);
          geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
              this.map.setCenter(result.position);
            } else {
              console.error('Geolocation failed: ', result.message);
            }
          });
        });

        this.initMarkers();
      })
      .catch(e => {
        console.log(e);
      });
    },
    initMarkers() {
      this.markers = this.points.map(point => {
        return new AMap.Marker({
          position: point.lnglat,
          map: this.map,
          extData: point,
        });
      });
    },
    showDistrictClusters() {
      Object.keys(this.districtPoints).forEach(district => {
        const points = this.districtPoints[district];
        const center = this.calculateCenter(points);
        const marker = new AMap.Marker({
          position: center,
          content: `<div class="amap-cluster">${district}<br>${points.length}个</div>`,
          offset: new AMap.Pixel(-20, -20),
          zIndex: 100,
        });
        marker.setMap(this.map);
      });
    },
    calculateCenter(points) {
      const lngSum = points.reduce((sum, point) => sum + point.lnglat[0], 0);
      const latSum = points.reduce((sum, point) => sum + point.lnglat[1], 0);
      return [lngSum / points.length, latSum / points.length];
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
.amap-cluster {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #fff;
  background: rgba(51,153,255,0.6);
  border-radius: 50%;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 20px;
  padding: 10px;
}
</style>
